package com.hd.controller.doc;

import com.hd.controller.base.BaseController;
import com.hd.entity.Attach;
import com.hd.entity.doc.article.Doc;
import com.hd.entity.enums.DocTypeEnum;
import com.hd.service.AttachService;
import com.hd.service.doc.article.DocService;
import com.hd.util.Const;
import com.hd.util.FileUtil;
import com.hd.util.StringUtils;
import com.hd.util.ZipUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
* 文件管理
*/
@RequestMapping("doc")
@Controller
public class DocController extends BaseController {
    @Autowired
    private DocService docService;
    @Autowired
    private AttachService attachService;
    /**
     * 主页
     * @return
     */


    @RequestMapping("manager")
    public String manager() {
        return "jsp/doc/docList";
    }

    /**
     * 作废列表
     * @return
     */
    @RequestMapping("manager2")
    public String manager2() {
        return "jsp/doc/docList2";
    }

    @RequestMapping("docSelect")
    public String docSelect(String id,Model model) {
        model.addAttribute("id",id);
        return "jsp/doc/docSelect";
    }
    @ResponseBody
    @RequestMapping("/get/{id}")
    public Object get(@PathVariable("id")String id){
        Doc doc=docService.get(id);
        return renderSuccess(doc);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@PathVariable("id") String id) {
        docService.delete(id);
        return renderSuccess("删除成功！");
    }

    /**
     * 作废
     * @param id
     * @return
     */
    @RequestMapping(value = "/cancel/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Object cancel(@PathVariable("id") String id) {
        docService.cancel(id);
        return renderSuccess("删除成功！");
    }

    /**
     * 还原
     * @param id
     * @return
     */
    @RequestMapping(value = "/updateBack/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Object updateBack(@PathVariable("id") String id) {
        docService.updateBack(id);
        return renderSuccess("还原成功！");
    }

    /**
     * 查询
     * @param pid
     * @return
     */
    @RequestMapping(value = "/findByPid",method = RequestMethod.POST)
    @ResponseBody
    public Object findByPid(String pid,Integer status){
        List<Doc> docList=docService.findByPid(pid,status);
        return renderSuccess(docList);
    }

    @RequestMapping("/save")
    @ResponseBody
    public Object save(Doc doc)throws Exception{
        docService.save(doc);
        return renderSuccess();
    }
    @RequestMapping("/saveFileformUpload")
    @ResponseBody
    public Object saveFileformUpload(Doc doc)throws Exception{
        Attach attach=attachService.get(doc.getAttachId());
        if(attach!=null){
            doc.setSize(getSize(attach.getSize()));
        }
        docService.save2(doc);
        return renderSuccess();
    }


    private String getSize(String size){
        Long l=Long.valueOf(size);
        if(l<1024L){
            return size+"b";
        }
        if(l<1024L*1024L){
            BigDecimal bg = new BigDecimal(l/1024).setScale(2, RoundingMode.UP);
            return bg.doubleValue()+"kb";
        }
        if(l<1024L*1024L*1024L){
            BigDecimal bg = new BigDecimal(l/(1024*1024)).setScale(2, RoundingMode.UP);
            return bg.doubleValue()+"MB";
        }
        if(l<1024L*1024L*1024L*1024L){
            BigDecimal bg = new BigDecimal(l/(1024*1024*1024)).setScale(2, RoundingMode.UP);
            return bg.doubleValue()+"GB";
        }
        return "0b";
    }

    /**
     * 修改文件名
     * @param id
     * @param name
     * @return
     */
    @RequestMapping("/updateFileName")
    @ResponseBody
    public Object updateFileName(String id,String name){
        docService.updateFileName(id,name);
        return renderSuccess();
    }

    /**
     * 移动文件
     * @param id
     * @param pid
     * @return
     */
    @RequestMapping("/updatePid")
    @ResponseBody
    public Object updatePid(String id,String pid){
        docService.updatePid(id,pid);
        return renderSuccess();
    }

    /**
     * 通过文件名查询
     * @param name
     * @param status
     * @return
     */
    @RequestMapping("/findByNameAndStatus")
    @ResponseBody
    public Object findByNameAndStatus(String name,Integer status){
        List<Doc> docs=new ArrayList<>();
        if(StringUtils.isNotNull(name)) {
           docs = docService.findByNameAndStatus(name, status);
        }else{
            docs=docService.findByPid("",status);
        }
        return renderSuccess(docs);
    }

    /**
     * 读取文件内容
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/readFile")
    public String readFile(String id,Model model){
        Doc doc=docService.get(id);
        Attach attach=attachService.get(doc.getAttachId());
        model.addAttribute("doc",doc);
        String content="";
        System.out.println(Const.BASE_UPLOAD_PATH+attach.getPath());
        content= FileUtil.readFile(Const.BASE_UPLOAD_PATH+attach.getPath());
        model.addAttribute("attachPath",Const.BASE_UPLOAD_PATH+attach.getPath());
        model.addAttribute("content",content);
        if(doc.getFileType().equals("md")){
            return "jsp/doc/readFileMd";
        }
        return "jsp/doc/readFile";
    }

    /**
     * 保存编辑文件内容
     * @param attachId
     * @param content
     * @return
     */
    @RequestMapping("/saveContent")
    @ResponseBody
    public Object saveContent(String id,String attachId,String content){
        Attach attach=attachService.get(attachId);
        String attachPath=Const.BASE_UPLOAD_PATH+attach.getPath();
        File f=new File(attachPath);
        System.out.println(attachPath);
        FileUtil.writeFile(attachPath,content);
        /**
         * 更新文件大小
         */
        Long size=FileUtil.getFileSize(f);
        docService.updateFileSize(id,attachId,size.toString(),getSize(size.toString()));
        return renderSuccess("保存成功");
    }

    /**
     * 下载文件
     * @param id
     */
    @RequestMapping("/download/{id}")
    public void download(@PathVariable("id") String id, HttpServletRequest request,
                         HttpServletResponse response)throws Exception{
        Doc doc=docService.get(id);
        //1)该文件是文件
        if(doc.getType()== DocTypeEnum.FILE.getType()){
            Attach attach = attachService.get(doc.getAttachId());
            String filename=attach.getName();
            String filePath=Const.BASE_UPLOAD_PATH+attach.getPath();
            download(filename,filePath,request,response);
        }

        //创建一个文件夹,用于保存压缩文件
        String dir=Const.BASE_UPLOAD_PATH+File.separator+"doc_down";
        String srcPath=dir;
        String zipPath=Const.BASE_UPLOAD_PATH;
        srcPath=srcPath.replace("//", "/");
        srcPath=srcPath.replace("/", "\\");
        zipPath=zipPath.replace("//", "/");
        zipPath=zipPath.replace("/", "\\");
        System.out.println(srcPath);
        System.out.println(dir);
        if(doc.getType()== DocTypeEnum.DIR.getType()){
           //2)如果是文件夹
             docService.createDownloadFile(id,dir);
            ZipUtils.zip(srcPath,zipPath, doc.getName() + ".zip");
            download(doc.getName() + ".zip",zipPath+File.separator+doc.getName() + ".zip",request,response);
            //删除创建的文件
            File dirFile=new File(dir);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }
            FileUtil.deleteChildrenFile(dirFile);
            dirFile.delete();
            File f=new File(zipPath+ File.separator+doc.getName()+".zip");
            f.delete();
            System.out.println("删除压缩文件"+zipPath+ File.separator+doc.getName()+".zip");
            System.out.println("删除文件："+dir);
        }
    }


}
